package org.whale.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.whale.dao.AppointmentOrderMapper;
import org.whale.entity.AppointmentOrder;
import org.whale.entity.DoctorScheduling;
import org.whale.service.AppointmentOrderService;
import org.whale.service.DoctorSchedulingService;

@Service
@Slf4j
public class AppointmentOrderServiceImpl extends ServiceImpl<AppointmentOrderMapper,AppointmentOrder> implements AppointmentOrderService {

    @Resource
    private DoctorSchedulingService doctorSchedulingService;


    @Override
    public AppointmentOrder getByIdCard(String idCard) {
        return super.getOne(new LambdaQueryWrapper<>(AppointmentOrder.class).eq(AppointmentOrder::getIdCard, idCard));
    }

    @Override
    public AppointmentOrder queryOrder(AppointmentOrder order) {
        return super.getOne(new LambdaQueryWrapper<>(AppointmentOrder.class)
                .eq(AppointmentOrder::getDept,order.getDept())
                .eq(AppointmentOrder::getIdCard,order.getIdCard())
                .eq(AppointmentOrder::getDate,order.getDate())
                .eq(AppointmentOrder::getTime,order.getTime())
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAppointmentOrder(AppointmentOrder appointmentOrder) {


        String hour = appointmentOrder.getTime().split("-")[0].split(":")[0];

        //扣减排班号数
        DoctorScheduling doctorScheduling = doctorSchedulingService.getOne(new LambdaQueryWrapper<>(DoctorScheduling.class)
                .eq(DoctorScheduling::getDate, appointmentOrder.getDate())
                .eq(DoctorScheduling::getDoctorName, appointmentOrder.getDoctorName())
                .le(DoctorScheduling::getTimeStart, hour)
                .ge(DoctorScheduling::getTimeEnd, hour)
                .eq(DoctorScheduling::getDept, appointmentOrder.getDept()));

        if(ObjectUtil.isNull(doctorScheduling)){
            throw new ArithmeticException("没有号源");
        }

        if(doctorScheduling.getNum() <= 0){
            throw new ArithmeticException("没有号源");
        }

        doctorScheduling.setNum(doctorScheduling.getNum()-1);
        doctorSchedulingService.updateById(doctorScheduling);

        appointmentOrder.setId(null);
        super.save(appointmentOrder);
    }
}
